package com.paul.dao;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.alibaba.fastjson.JSON;
import com.domain.User;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;


/** 这是一个标准的javadoc注释
 * 这是一个继承接口的类
 * @author Paul
 *@Time 2016-09-17
 */

@Repository("userDao")
public class UserDaoImpl implements UserDao {

	@Autowired
	public SqlSessionTemplate sqlSessionTemplate;	
	
	/*
	// mybatis公共代码部分
	String resource = "conf.xml";

	InputStream is = UserDaoImpl.class.getClassLoader().getResourceAsStream(resource);
	SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
	SqlSession session = sessionFactory.openSession();
	*/
	
	// 查询用户
	public Map<String, Object> search(Map<String, Object> params) {
		Map<String, Object> aMap = new HashMap<String, Object>();

		String statement = "com.dao.userDao.getUserTotal";
		int total = sqlSessionTemplate.selectOne(statement, params);
		statement = "com.dao.userDao.getUser";

		List<String> al = sqlSessionTemplate.selectList(statement, params);

		String jsonString = JSON.toJSONString(al);

		aMap.put("pageCount",params.get("pageCount"));
		aMap.put("pageSize",params.get("pageSize"));
		aMap.put("total", total);
		aMap.put("rows", jsonString);
		
		/*sqlSessionTemplate.commit();
		sqlSessionTemplate.close();*/

		return aMap;

	}

	// 验证用户
	public String check(String username) {

		String statement = "com.dao.userDao.checkUser";
		String result = sqlSessionTemplate.selectOne(statement, username);

		/*sqlSessionTemplate.commit();
		sqlSessionTemplate.close();*/
		return result;
	};

	// 编辑用户
	public int update(User user) {

		String statement = "com.dao.userDao.updateUser";
		int result = sqlSessionTemplate.update(statement, user);
		/*sqlSessionTemplate.commit();
		sqlSessionTemplate.close();*/

		return result;
	};

	// 删除用户
	public int delete(String userId) {

		String statement = "com.dao.userDao.deleteUser";
		int result = sqlSessionTemplate.delete(statement, userId);

		/*sqlSessionTemplate.commit();
		sqlSessionTemplate.close();*/

		return result;
	};

	// Dao层添加用户
	public int insert(User user) {

		String statement = "com.dao.userDao.insertUser";
		int result = sqlSessionTemplate.insert(statement, user);

		/*sqlSessionTemplate.commit();
		sqlSessionTemplate.close();*/

		return result;

	}

	
	public SqlSessionTemplate getSqlSessionTemplate() {
		return sqlSessionTemplate;
	}
	
	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	};
	
	
	

}
